<template>
  <div class="app-container">    
    <el-row v-if="optType != 'view'" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:wm:issueheader:edit','mes:pro:issueheader:edit']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:wm:issueheader:edit','mes:pro:issueheader:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteAll"
          v-hasPermi="['mes:wm:issueheader:edit','mes:pro:issueheader:edit']"
        >删除</el-button>
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="issueData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品物料名称" width="120px"  align="center" prop="itemName" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-link type="danger" v-if="isStock" @click="handleStock(scope.row)">{{scope.row.itemName}}</el-link>
          <span v-else>{{scope.row.itemName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品物料编码" width="120px" align="center" prop="itemCode" />
      <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="使用比例" align="center" prop="useQuantity" />
      <el-table-column label="领料数量" width="240px" align="center" prop="quantityIssued" >
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.quantityIssued" controls-position="right" :min="1" :max="scope.row.quantityOnhand"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="库区名称" align="center" prop="locationName" />
      <el-table-column label="库位名称" align="center" prop="areaName" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" v-if="optType != 'view'" width="100px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="optType != 'view'"
            v-hasPermi="['mes:wm:issueheader:edit','mes:pro:issueheader:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index, scope.row)"
            v-if="optType != 'view'"
            v-hasPermi="['mes:wm:issueheader:edit','mes:pro:issueheader:edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="issueData.length > 0">
      <el-form size="small" :inline="true" label-width="600px">
        <el-form-item label="批量修改领料数量" style="padding-top: 10px;">
          <el-input-number
            v-model="allNum"
            controls-position="right" 
            :min="0"
            clearable
            size="small"
            @change="changeAllNum"
          />
        </el-form-item>
      </el-form>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <StockSelect 
      ref="stockSelect" 
      v-if="showItemSelect" 
      @closeSelect="closeSelect" 
      :batchCode="form.batchCode" 
      :vendorId="form.vendorId" 
      :materialStockIds="materialStockIds"
      @onSelected="onStockSelected"
    >
    </StockSelect>

    <el-dialog title="选择库存" :visible.sync="openView" width="80%" append-to-body>
      <el-table ref="multipleTable" v-loading="loading" :data="bomList" @selection-change="handleSelectionChangeBom">
        <el-table-column type="selection" width="55" />
        <el-table-column label="产品物料名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
        <el-table-column label="产品物料编码" align="center" prop="itemCode" :show-overflow-tooltip="true"/>
        <el-table-column label="规格型号" width="240px" align="center" prop="specification" :show-overflow-tooltip="true"/>
        <el-table-column label="使用比例" width="90px" align="center" prop="useQuantity" />
        <el-table-column label="在库数量" align="center" prop="quantityOnhand" />
        <el-table-column label="单位" align="center" prop="unitOfMeasure" />
        <el-table-column label="入库批次号" width="100px" align="center" prop="batchCode" :show-overflow-tooltip="true"/>
        <el-table-column label="仓库" align="center" prop="warehouseName" />
        <el-table-column label="库区" align="center" prop="locationName" />
        <el-table-column label="库位" align="center" prop="areaName" />
        <el-table-column label="供应商编号" width="100px" align="center" prop="vendorCode" />
        <el-table-column label="供应商名称" align="center" prop="vendorName" :show-overflow-tooltip="true"/>
        <el-table-column label="供应商简称" width="100px" align="center" prop="vendorNick" />
        <el-table-column label="生产工单号" width="150px" align="center" prop="workorderCode" />
        <el-table-column label="库存有效时间" align="center" prop="recptDate" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.recptDate) }}</span>
            </template>
          </el-table-column>
      </el-table>
      <pagination
        v-show="total1>0"
        :total="total1"
        :page.sync="queryParams1.pageNum"
        :limit.sync="queryParams1.pageSize"
        @pagination="getBomList"
      />

      <template slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelectBom">确 定</el-button>
        <el-button @click="openView=false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listIssueline, getIssueline, delIssueline, addIssueline, updateIssueline } from "@/api/mes/wm/issueline";
import { listBomStock, listStockBom } from "@/api/mes/md/bom";
import StockSelect from "@/components/stockSelect/singleSimple.vue"
export default {
  name: "Issueline",
  components:{StockSelect},
  props:{
    optType: null,
    issueId: null,
    warehouseId: null,
    locationId: null,
    areaId: null,
    productId: null,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组
      ids1: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      total1: 0,
      // 生产领料单行表格数据
      issuelineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        issueId: this.issueId,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityIssued: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemId: [
          { required: true, message: "产品物料不能为空", trigger: "blur" }
        ],
        quantityIssued: [
          { required: true, message: "领料数量不能为空", trigger: "blur" }
        ],
      },
      showItemSelect: true, // 是否显示物料选择
      materialStockIds: [], // 物料库存id
      fromWorkerBomList: [], // 从工单bom列表中获取的物料数据
      isStock: this.$route.fullPath=='/mes/wm/issue'?true:false, // 是否是库存领料
      openView: false, // 是否显示bom弹窗
      bomList: [], // bom列表
      allNum: null, // 总领料数量
    };
  },
  computed:{
    issueData(){
      return [...this.fromWorkerBomList, ...this.issuelineList]
    }
  },
  watch: {
    issueData: {
      handler(newVal, oldVal) {
        this.$emit('onAddLine', newVal);
      },
      deep: true
    },
    productId: {
      handler(newVal, oldVal) {
        console.log("watch productId", newVal);
        if(newVal){
          this.queryParams.itemId = newVal;
          listBomStock(this.queryParams).then(res=>{
            this.fromWorkerBomList = res.rows.map(item => {
              return {
                ...item,
                suuid: this.sUuid(),
              }
            });
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    console.log(this.$route.fullPath,'))))))))))))');
    if(this.optType!=="add"){
      this.getList();
      listIssueline({pageNum: 1,pageSize: 10000,issueId: this.issueId}).then(response => {
        response.rows.forEach(item => {
          this.materialStockIds.push(item.materialStockId)
        })
      });
    }else{
      this.loading = false;
    }
  },
  methods: {
    /** 查询生产领料单行列表 */
    getList() {
      this.loading = true;
      listIssueline(this.queryParams).then(response => {
        // this.issuelineList = response.rows
        this.issuelineList = response.rows.map(item => {
          return {
            ...item,
            suuid: this.sUuid()
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.suuid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.open = true;
      // this.title = "添加生产领料单行";
      this.handleSelectStock()
    },
    /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   const lineId = row.lineId || this.ids
    //   getIssueline(lineId).then(response => {
    //     //debugger;
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改生产领料单行";
    //   });
    // },
    /** 提交按钮 */
    submitForm() {
      const valid = this.issueData.every(item => {
        return item.itemName && item.quantityIssued>=0;
      })
      return valid;
    },
    /** 删除按钮操作 */
    handleDelete(ind,row) {
      this.$modal.confirm('是否确认删除该数据项？').then(()=>{
        // this.issueData.splice(ind,1);
        this.fromWorkerBomList = this.fromWorkerBomList.filter(item => item.suuid !== row.suuid)
        this.issuelineList = this.issuelineList.filter(item => item.suuid !== row.suuid)
        this.materialStockIds.splice(ind,1);
        if(row.lineId){
          delIssueline(row.lineId).then(res=>{
            if(res.code === 200){
              this.getList();
              this.$modal.msgSuccess("删除成功");
            }
          });
        }else{
          this.$modal.msgSuccess("删除成功");
        }
      }).catch(() => {});
    },
    handleSelectStock(){
      this.$refs.stockSelect.showFlag = true;
      this.$refs.stockSelect.getList();
    },
        //物料选择弹出框
    onStockSelected(obj){
      console.log(obj, 'onStockSelected');
      if(obj != undefined && obj != null){
        obj.forEach(item=>{
          this.fromWorkerBomList.push({...item, suuid: this.sUuid()})
          this.materialStockIds.push(item.materialStockId)
        })
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/issueline/export', {
        ...this.queryParams
      }, `issueline_${new Date().getTime()}.xlsx`)
    },
    closeSelect(){
      this.showItemSelect = false;
      setTimeout(()=>{
        this.showItemSelect = true;
      }, 200)
    },
    handleDeleteAll(){
      this.$modal.confirm('是否确认删除选中数据项？').then(()=>{
        let lineIds = [] 
        this.ids.forEach(id => {
          const index = this.issueData.findIndex(item => item.suuid === id);
          // this.materialStockIds.splice(index,1);
          if(this.issueData[index].lineId){
            lineIds.push(this.issueData[index].lineId)
          }
          this.fromWorkerBomList = this.fromWorkerBomList.filter(item => item.suuid !== id)
          this.issuelineList = this.issuelineList.filter(item => item.suuid !== id)
          this.materialStockIds.splice(index,1);
        })
        if(lineIds.length>0){
          delIssueline(lineIds.join(",")).then(res=>{
            if(res.code === 200){
              this.getList();
              // this.$modal.msgSuccess("删除成功");
            }
          })
        }
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 打开仓库BOM选择
    handleStock(row){
      this.openView = true;
      this.queryParams1.itemId = row.itemId;
      this.getBomList();
    },
    getBomList(){
      this.loading = true;
      listStockBom(this.queryParams1).then(res=>{
        this.bomList = res.rows;
        this.loading = false;
        this.total1 = res.total;
        console.log(res, 'handleStock');
      })
    },
    handleSelectionChangeBom(selection) {
      this.ids1 = selection.map(item => item.itemId)
    },
    confirmSelectBom(){
      
      console.log(111);
    },
    changeAllNum(){
      this.issueData.forEach(item => {
        item.quantityIssued = this.allNum;
      })
      console.log(this.allNum);
    }
  }
};
</script>
